﻿using System;
using System.Collections.Generic;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class IndexRecord : BiffRecord
    {
        private uint rwMic;
        private uint rwMac;
        private uint ibXF;
        private List<uint> rgibRw = new List<uint>();

        internal IndexRecord(Worksheet worksheet, List<WorksheetSequencer.RowGroup> rowGroups)
        {
            var usedRange = worksheet.UsedRange;
            this.rwMic = (uint) usedRange.Row;
            this.rwMac = (uint) (usedRange.Row + usedRange.RowSpan);
            rgibRw = new List<uint>(Enumerable.Select(rowGroups, r => (uint) 0));
        }

        public IndexRecord()
        {
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            context.ReadUInt32();//\\ reserved;
            this.rwMic = context.ReadUInt32();
            this.rwMac = context.ReadUInt32();
            this.ibXF = context.ReadUInt32();
            int count = (length - 16)/4;
            for (int i = 0; i < count; i++)
            {
                rgibRw.Add(context.ReadUInt32());
            }
        }

        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.Index; }
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            context.Write((uint)0);
            context.Write(rwMic);
            context.Write(rwMac);
            context.DefColumnWidthInIndex = (context.Position);
            context.Write(ibXF);
            context.DBCellPosition = context.Position;
            foreach (var i in this.rgibRw)
                context.Write(i); //\\useless here
        }
    }
}